<?php
namespace addons\jieziad\service;

use addons\jiezicommon\traits\Singleton;

class Ad
{
    use Singleton;
    public function pos_info($pos_id)
    {
        $ad_model = new \addons\jieziad\model\Jieziad();

        $table = $ad_model->alias('a')->join('jieziad_position p', 'a.ad_position_id = p.id')->where('a.ad_position_id', $pos_id)->where('p.is_open', 1)->where('a.enabled_switch', 1);
        $ad_list = $table->order('a.weigh asc')->column('a.id, a.ad_name, a.ad_image, a.start_time, a.end_time, a.media_type, a.ad_type, a.ad_val, a.params');
        $return_data = [];
        $now = request()->time();
        if (!empty($ad_list)) {
            foreach ($ad_list as $ad) {
                if ($ad['start_time'] && $ad['start_time'] > $now) {
                    continue;
                }
                if ($ad['end_time'] && $ad['end_time'] < $now) {
                    continue;
                }
                $ad['ad_image'] = cdnurl($ad['ad_image'], true);
                unset($ad['params'], $ad['start_time'], $ad['end_time']);
                $ad['img'] = $ad['ad_image'];
                $return_data[] = $ad;
            }
        }

        return $return_data;
    }

    public function pos_infos($pos_ids)
    {
        $ad_model = new \addons\jieziad\model\Jieziad();

        $table = $ad_model->alias('a')->join('jieziad_position p', 'a.ad_position_id = p.id')->whereIn('a.ad_position_id', $pos_ids)->where('p.is_open', 1)->where('a.enabled_switch', 1);
        $ad_list = $table->order('a.ad_position_id, a.weigh asc')->column('a.id, a.ad_position_id, a.ad_name, a.ad_image, a.start_time, a.end_time, a.media_type, a.ad_type, a.ad_val, a.params');
        $return_data = [];
        $now = request()->time();
        $domain = request()->domain();
        // var_dump($table->getLastSql(), $ad_list);die;
        if (!empty($ad_list)) {
            foreach ($ad_list as $ad) {
                if ($ad['start_time'] && $ad['start_time'] > $now) {
                    continue;
                }
                if ($ad['end_time'] && $ad['end_time'] < $now) {
                    continue;
                }

                $ad['ad_image'] = cdnurl($ad['ad_image'], true);
                unset($ad['params'], $ad['start_time'], $ad['end_time']);

                $return_data[$ad['ad_position_id']][] = $ad;
            }
        }

        return $return_data;
    }
}
